import { dialog, ipcMain, IpcMainInvokeEvent } from 'electron';
import * as dfd from 'danfojs-node';
import Log from '../../util/Log';
import DataFrameUtil from '../../util/dataframe-util';
import FileUtil from '../../util/file-util';
import { IPCCommnd } from '../../const';
import PretreatUtil from '../../util/pretreat-util';

const TAG = 'IPCManager';

class IPCManager {
  private static instance: IPCManager;

  public static getInstance() {
    if (!this.instance) {
      this.instance = new IPCManager();
    }
    return this.instance;
  }

  public showErrorMessage = async (
    event: IpcMainInvokeEvent,
    title: string,
    content: string
  ) => {
    dialog.showErrorBox(title, content);
  };

  public showMessage = async (
    event: IpcMainInvokeEvent,
    title: string,
    content: string
  ) => {
    dialog.showErrorBox(title, content);
  };

  public getColumn = async (event: IpcMainInvokeEvent, filename: string) => {
    const df = await DataFrameUtil.getInstance().readExcel(filename);
    if (df) {
      return df.columns;
    }
    return df;
  };

  public doMerge = async (
    event: IpcMainInvokeEvent,
    filename1: string,
    filename2: string,
    exportPath: string,
    twoCols: string[],
    exportCols: string[]
  ) => {
    DataFrameUtil.getInstance()
      .doTwoColsMerge(filename1, filename2, twoCols, exportCols)
      .then((df) => {
        dfd.toExcel(df, {
          filePath: exportPath,
        });
        return '';
      })
      .catch((err) => {
        Log.e(TAG, err);
      });
  };

  public ipcRegisterHandler = () => {
    ipcMain.handle(IPCCommnd.ChooseFiles, FileUtil.getInstance().chooseFiles);
    ipcMain.handle(IPCCommnd.ChooseDir, FileUtil.getInstance().chooseDir);
    ipcMain.handle(
      IPCCommnd.VerifyCertificate,
      FileUtil.getInstance().verifyCertificate
    );
    ipcMain.handle(
      IPCCommnd.ImportCertificate,
      FileUtil.getInstance().importCertificate
    );
    ipcMain.handle(
      IPCCommnd.ChooseSingleFile,
      FileUtil.getInstance().chooseSingleFile
    );
    ipcMain.handle(IPCCommnd.GetColumn, this.getColumn);
    ipcMain.handle(IPCCommnd.ShowError, this.showErrorMessage);
    ipcMain.handle(IPCCommnd.DoMerge, this.doMerge);
    ipcMain.handle(IPCCommnd.ShowMessage, this.showMessage);
    ipcMain.handle(IPCCommnd.MainExportLog, Log.getInstance().exportLog);
    ipcMain.handle(
      IPCCommnd.VerticalMerge,
      DataFrameUtil.getInstance().verticalMerge
    );
    ipcMain.handle(IPCCommnd.CsvToExcel, PretreatUtil.getInstance().csvToExcel);
    ipcMain.handle(IPCCommnd.MainLog, Log.renderLog);
    Log.i(TAG, 'ipcRegisterHandler');
  };
}
export default IPCManager;
